package com.zjh.springcloud.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String uri=request.getRequestURI();

        String[] allows={"/accountClient/toLogin","/login.html","accountClient/login","accountClient/logout"};

        for(String allow:allows){
            if(uri.contains(allow)){
                filterChain.doFilter(request,response);
                return;
            }
        }

        HttpSession session=request.getSession();
        Object obj = session.getAttribute("obj");
        if(obj==null){
            response.sendRedirect("/accountClient/toLogin");
            return;
        }
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
